<template>
  <div class="login-container flx-center">
    <div class="login-box">
      <div class="switch-dark">
        <el-switch
          v-model="settingStore.isDark"
          @change="changeDark"
          inline-prompt
          active-icon="Sunny"
          inactive-icon="Moon"
        />
      </div>
      <div class="login-left">
        <img
          class="login-left-img"
          src="@/assets/images/login_left.svg"
          alt="login"
        />
      </div>
      <div class="login-form">
        <div class="login-logo">
          <img class="login-icon" :src="setting.imgSrc" alt="" />
          <h2 class="logo-text">{{ setting.title2 }}</h2>
        </div>

        <el-form
          ref="loginFormRef"
          size="large"
          :model="loginForm"
          :rules="rules"
          status-icon
        >
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              :prefix-icon="User"
            >
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              show-password
              autocomplete="new-password"
            >
              <template #prefix>
                <el-icon class="el-input__icon">
                  <lock />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <div class="login-btn">
          <el-button :icon="CircleClose" round size="large"> 重置 </el-button>
          <el-button
            :icon="UserFilled"
            round
            size="large"
            type="primary"
            @click="submitForm(loginFormRef)"
            :loading="loading"
          >
            登录
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { CircleClose, User, UserFilled, Lock } from "@element-plus/icons-vue";
import { useRouter, useRoute } from "vue-router";
import { h } from "vue";
import { useUserStore } from "@/store/modules/user";
import { ElMessage, ElNotification } from "element-plus";
import { getTimePeriod } from "@/utils/util";
import type { FormInstance, FormRules } from "element-plus";
import setting from "@/setting.ts";
import { useDark, useToggle } from "@vueuse/core";
import { useSettingStore } from "@/store/modules/setting.ts";

interface RuleForm {
  username: string;
  password: string;
}
let settingStore = useSettingStore();
const rules = reactive<FormRules<RuleForm>>({
  username: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { min: 5, max: 10, message: "请输入5到10位的字符", trigger: "blur" },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    // 自定义校验规则
    {
      validator: (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error("密码长度不能小于6位"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
});
const loading = ref(false);
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const loginForm = reactive({
  username: "admin",
  password: "111111",
});

const loginFormRef = ref();

//switch开关的chang事件进行暗黑模式的切换
const isDark = useDark();
const changeDark = useToggle(isDark);
/**
 * 提交表单函数
 * @param {FormInstance | undefined} formEl - 表单实例，用于执行表单验证
 */
const submitForm = async (formEl: FormInstance | undefined) => {
  // 检查表单实例是否存在
  if (!formEl) return;

  // 执行表单验证
  await formEl.validate((valid, fields) => {
    // 验证通过
    if (valid) {
      console.log("submit!");
      login();
    } else {
      // 验证失败，输出错误信息
      console.log("error submit!", fields);
    }
  });
};
/**
 * 登录函数
 * 此函数负责处理用户登录的逻辑，包括设置加载状态、执行登录操作、处理登录成功后的跳转和提示，以及登录失败的错误处理
 */
const login = () => {
  // 登录操作开始时，设置加载状态为true
  loading.value = true;

  // 调用userStore的login方法尝试登录
  userStore
    .login(loginForm)
    .then((res) => {
      // 登录成功后，打印响应结果，并将加载状态重置为false
      console.log("res", res);
      loading.value = false;
      // 获取路由参数，用于判断是否需要跳转到特定页面
      const redirect: any = route.query.redirect;
      // 登录成功后跳转到主页
      router.push(redirect || "/");

      // 显示成功登录的通知，包括问候语和欢迎信息
      ElNotification({
        type: "success",
        title: `Hi，${getTimePeriod()}好`,
        message: h("i", { style: "color: teal" }, "欢迎回来👏"),
      });
    })
    .catch((err) => {
      // 登录失败时，打印错误信息，并将加载状态重置为false
      console.log("err:", err);
      loading.value = false;

      // 显示登录失败的错误消息
      ElMessage.error(err);
    });
};
</script>

<style scoped lang="scss">
.flx-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-container {
  height: 100%;
  min-height: 550px;
  background-color: var(--el-bg-color-page);
  background-image: url("@/assets/images/login_bg.svg");
  background-size: 100% 100%;
  background-size: cover;

  .login-box {
    position: relative;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-around;
    width: 96.5%;
    height: 94%;
    padding: 0 50px;
    background-color: var(--login-bg-inner-color);
    border-radius: 10px;

    .switch-dark {
      position: absolute;
      top: 13px;
      right: 18px;
    }

    .login-left {
      width: 800px;
      margin-right: 10px;

      .login-left-img {
        width: 100%;
        height: 100%;
      }
    }

    .login-form {
      width: 420px;
      padding: 50px 40px 45px;
      background-color: var(--el-bg-color);
      border-radius: 10px;
      box-shadow: rgb(0 0 0 / 10%) 0 2px 10px 2px;

      .login-logo {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 45px;

        .login-icon {
          width: 55px;
          height: 55px;
        }

        .logo-text {
          padding: 0 0 0 25px;
          margin: 0;
          font-size: 30px;
          font-weight: bold;
          color: var(--theme-font);
          white-space: nowrap;
        }
      }

      .el-form-item {
        margin-bottom: 40px;
      }

      .login-btn {
        display: flex;
        justify-content: space-between;
        width: 100%;
        margin-top: 40px;
        white-space: nowrap;

        .el-button {
          width: 185px;
        }
      }
    }
  }
}

@media screen and (width <=1250px) {
  .login-left {
    display: none;
  }
}

@media screen and (width <=600px) {
  .login-form {
    width: 97% !important;

    .login-logo {
      .login-icon {
        width: 35px !important;
        height: 35px !important;
      }

      .logo-text {
        padding: 0 0 0 15px !important;
        font-size: 20px !important;
      }
    }
  }
}
</style>
